package com.wskj.obs.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.wskj.common.utils.file.FileUploadUtils;
import com.wskj.obs.service.IObsService;
import com.wskj.system.domain.SysCommon;
import com.wskj.system.service.ISysCommonService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * redis的过期键信息Service业务层处理
 *
 * @author wsdz
 * @date 2022-09-29
 */
@Service
@AllArgsConstructor
public class ObsServiceImpl implements IObsService {

    private final ISysCommonService iSysCommonService;

    @Override
    public Map<String, Object> uploadByHuaWei(MultipartFile file) throws Exception {
        // 华为云Endpoint
        SysCommon one = iSysCommonService.getById(1000034L);
        // 华为云账号accessKeyId
        SysCommon two = iSysCommonService.getById(1000036L);
        // 华为云账号accessKeySecret
        SysCommon three = iSysCommonService.getById(1000037L);
        // 华为云Bucket名称
        SysCommon four = iSysCommonService.getById(1000035L);
        ObsClient obsClient = new ObsClient(two.getCommonValue(), three.getCommonValue(), one.getCommonValue());
        String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        // 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String completePath = getPath(suffix);
        PutObjectResult result = obsClient.putObject(four.getCommonValue(), completePath, inputStream);
        // 关闭OSSClient。
        obsClient.close();
        Map<String, Object> returnMap = new HashMap<>();
        String prefixUrl  = "https://"+four.getCommonValue()+"."+one.getCommonValue();
        returnMap.put("fullUrl", prefixUrl+"/"+result.getObjectKey());
        returnMap.put("halfUrl", result.getObjectKey());
        return returnMap;
    }

    @Override
    public Map<String, Object> uploadByTencent(MultipartFile file) throws Exception {
        // 腾讯云Bucket域名
        SysCommon one = iSysCommonService.getById(1000049L);
        // 腾讯云账号accessKeyId
        SysCommon two = iSysCommonService.getById(1000052L);
        // 腾讯云账号accessKeySecret
        SysCommon three = iSysCommonService.getById(1000053L);
        // 腾讯云Bucket名称
        SysCommon four = iSysCommonService.getById(1000050L);
        // 腾讯云所属地域
        SysCommon five = iSysCommonService.getById(1000051L);
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(two.getCommonValue(), three.getCommonValue());
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(five.getCommonValue());
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        // 上传文件流。
        InputStream inputStream = new ByteArrayInputStream(file.getBytes());
        ;
        String completePath = getPath(suffix);
        // 上传文件
        cosClient.putObject(new PutObjectRequest(four.getCommonValue(), completePath, inputStream, null));
        cosClient.setBucketAcl(four.getCommonValue(), CannedAccessControlList.PublicRead);
        cosClient.shutdown();
        String url = one.getCommonValue() + "/" + completePath;
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("fullUrl", url);
        returnMap.put("halfUrl", completePath);
        return returnMap;
    }

    @Override
    public Map<String, Object> uploadByOss(MultipartFile file) throws Exception {
        // 阿里云Endpoint
        SysCommon one = iSysCommonService.getById(1000038L);
        // 阿里云账号accessKeyId
        SysCommon two = iSysCommonService.getById(1000041L);
        // 阿里云账号accessKeySecret
        SysCommon three = iSysCommonService.getById(1000042L);
        // 阿里云Bucket名称
        SysCommon four = iSysCommonService.getById(1000039L);
        // 阿阿里云Bucket域名
        SysCommon five = iSysCommonService.getById(1000040L);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(one.getCommonValue(), two.getCommonValue(), three.getCommonValue());
        String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        // 上传文件流。
        InputStream inputStream = inputStream = new ByteArrayInputStream(file.getBytes());
        ;
        String completePath = getPath(suffix);
        ossClient.putObject(four.getCommonValue(), completePath, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        String src = five.getCommonValue() + "/" + completePath;
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("fullUrl", src);
        returnMap.put("halfUrl", completePath);
        return returnMap;
    }

    @Override
    public Map<String, Object> uploadByLocal(MultipartFile file) throws Exception {
        // 服务域名配置
        SysCommon one = iSysCommonService.getById(1000048L);
        // 本地文件存储路径
        SysCommon two = iSysCommonService.getById(1000047L);
        String[] split = one.getCommonValue().split("://");
        // 上传文件路径
        String filePath = two.getCommonValue();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = one.getCommonValue() + fileName;
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("fullUrl", url);
        returnMap.put("halfUrl", filePath);
        return returnMap;
    }

    private String getPath(String suffix) {
        // 生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 文件路径
        String path = "upload" + "/" + format(new Date()) + "/" + uuid;
        return path + suffix;
    }

    private String format(Date date) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            return df.format(date);
        }
        return null;
    }
}
